package com.alibaba.algo.excellistener;

import com.alibaba.algo.domain.user.SysGroupDomain;
import com.alibaba.algo.entity.user.SysGroup;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.*;

public class SysGroupListener extends AnalysisEventListener<SysGroup> {

    private static final Logger log = LoggerFactory.getLogger(SysGroupListener.class);

    List<SysGroup> dataList = new ArrayList<>();

    private final List<String> errorList = new ArrayList<>();

    private final SysGroupDomain groupDomain;

    private SysGroupListener() {
        this.groupDomain = new SysGroupDomain();
    }

    public SysGroupListener(SysGroupDomain groupDomain) {
        this.groupDomain = groupDomain;
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        log.info("import group headMap={}", JSON.toJSONString(headMap));
        Collection<String> values = headMap.values();
        if (!values.contains("人员组编码")) {
            throw new RuntimeException("缺少人员组编码列，请上传正确的文件。");
        }
        if (!values.contains("人员组名称")) {
            throw new RuntimeException("缺少人员组名称列，请上传正确的文件。");
        }
    }

    @Override
    public void invoke(SysGroup data, AnalysisContext context) {
        if (ObjectUtils.isEmpty(data)) {
            errorList.add("第" + context.readRowHolder().getRowIndex() + "行数据为空，请检查");
        }
        if (ObjectUtils.isEmpty(data.getGroupCode())) {
            errorList.add("第" + context.readRowHolder().getRowIndex() + "行人员组编码为空，请检查");
        }
        if (ObjectUtils.isEmpty(data.getGroupName())) {
            errorList.add("第" + context.readRowHolder().getRowIndex() + "行人员组名称为空，请检查");
        }
        dataList.add(data);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (CollectionUtils.isEmpty(dataList)) {
            return;
        }
        Collections.synchronizedList(dataList).parallelStream().forEach(item -> groupDomain.save(item));
    }
}
